package com.example.rlw.mvpplugintest.mvp;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by rlw on 2018/10/12.
 * presenter 基类实现
 */

public class BasePresenterImpl<V extends BaseView> implements BasePresenter<V> {

    protected WeakReference<V> mView;
    CompositeDisposable mDisposables;

    /**
     * 如果当前页面不需要操作数据,只需要 View 层,则使用此构造函数
     *
     * @param rootView
     */
    public BasePresenterImpl(V rootView) {
        this.mView = new WeakReference<V>(rootView);
    }

    public BasePresenterImpl() {

    }

    @Override
    public void attachView(V view) {
        if (mView == null) {
            mView = new WeakReference<V>(view);
        }
    }

    @Override
    public void detachView() {
        mView.clear();
        mView = null;
        dispose();
    }

    public V getView() {
        if (mView != null) {
            return mView.get();
        }
        return null;
    }

    //取消所有的订阅
    public void dispose() {
        if (mDisposables != null) {
            mDisposables.clear();
        }
    }

    protected void addSubscription(Disposable disposable) {
        if (disposable == null) return;
        if (mDisposables == null) {
            mDisposables = new CompositeDisposable();
        }
        mDisposables.add(disposable);
    }

}
